package com.imay.live.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.imay.base.util.StringUtil;
import com.imay.capturefilter.utils.ICUtils;
import com.imay.dialog.Dialoger;
import com.imay.live.R;
import com.imay.live.activity.user.util.NameLengthFilter;
import com.imay.live.activity.user.util.NickFilter;
import com.imay.live.cache.UserInfoCache;
import com.imay.live.helper.DialogFragmentHelper;
import com.imay.live.helper.EventHelper;
import com.imay.live.helper.MediaHelper;
import com.imay.live.logic.ProfileEditActivityLogic;
import com.imay.live.manager.SensitiveWordFilterManager;
import com.imay.live.model.SensitiveWordResult;
import com.imay.live.model.UserInfoModel;
import com.imay.live.proto.ErrorResult;
import com.imay.live.proto.Result;
import com.imay.live.proto.ResultNoData;
import com.imay.live.proto.helper.ProtoCallBack;
import com.imay.live.proto.helper.ProtoHttpFactory;
import com.imay.live.proto.helper.ProtoRequestHelper;
import com.imay.live.utils.AppUtil;
import com.imay.live.utils.GlideUtil;
import com.imay.live.utils.ToastUtil;
import com.imay.tbas_api.IMYTBASObject;
import com.yalantis.ucrop.UCrop;

import java.io.File;

import static com.imay.dialog.Dialoger.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE;
import static com.imay.dialog.Dialoger.SYS_IMAGE_ACTIVITY_REQUEST_CODE;
import static com.imay.live.proto.ResultCode.CodeSuccess;
import static com.taobao.accs.ACCSManager.mContext;

/**
 * create by nick
 * 我的->设置->个人资料
 */
public class ProfileEditActivity extends BaseRequestActivity implements  View.OnClickListener, ProtoCallBack {

    private ProfileEditActivityLogic mLogic;

    private ImageView iv_head_img_profile_edit;
    private EditText et_nickname_profile_edit;
    private TextView tv_sex_profile_edit;
    private EditText et_website_profile_edit;
    private EditText et_intro_profile_edit;
    private TextView tv_age_profile_edit;
    private TextView tv_phone_profile_edit;
    private EditText et_email_profile_edit;
    private String imagePath;
    private String resultUrl;
    private UserInfoModel userModel;
    private int sex;
    private int age =-1;
    private IMYTBASObject userInfoChangeListener;
    private TextView tv_profile_edit_text_number;

    public static void start(Context context) {
        Intent starter = new Intent(context, ProfileEditActivity.class);
        context.startActivity(starter);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_profile_edit;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        setTitle(getString(R.string.setting_profile_modify));

        getTitleBar().addRightTextView(getString(R.string.save));
        mLogic = new ProfileEditActivityLogic(this);
        bindViews();
        addListener();
        userModel = UserInfoCache.getUserInfo();
        if (userModel!=null){
            age=userModel.getAge();
        }
        refreshView();
        initUserInfoChangeListener();

    }



    private void bindViews() {

        iv_head_img_profile_edit = $(R.id.iv_head_img_profile_edit);
        et_nickname_profile_edit = $(R.id.et_nickname_profile_edit);
        tv_sex_profile_edit = $(R.id.tv_sex_profile_edit);
        et_website_profile_edit = $(R.id.et_website_profile_edit);
        tv_age_profile_edit = $(R.id.tv_age_profile_edit);
        tv_phone_profile_edit = $(R.id.tv_phone_profile_edit);
        et_email_profile_edit = $(R.id.et_email_profile_edit);
        et_intro_profile_edit = $(R.id.et_intro_profile_edit);
        tv_profile_edit_text_number = $(R.id.tv_profile_edit_text_number);

        NickFilter nickFilter = new NickFilter();
        NameLengthFilter filter = new NameLengthFilter(16);
        InputFilter[] filters = new InputFilter[]{filter,nickFilter};
        et_nickname_profile_edit.setFilters(filters);


    }


    private void addListener() {
        getTitleBar().setRightTextOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateUserInfo();
            }
        });
        iv_head_img_profile_edit.setOnClickListener(this);
        tv_sex_profile_edit.setOnClickListener(this);
        tv_age_profile_edit.setOnClickListener(this);
        tv_sex_profile_edit.setOnClickListener(this);
        $(R.id.ll_profile_edit_phone).setOnClickListener(this);
        et_intro_profile_edit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                tv_profile_edit_text_number.setText(300-s.length()+"");
//                tv_profile_edit_text_number.setTextColor(300<s.length()?getResources().getColor(R.color.unread_point_bg):getResources().getColor(R.color.text_75));
            }
        });

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_head_img_profile_edit:
                MediaHelper.showMediaSheet(this);
                break;
            case R.id.tv_sex_profile_edit:
                mLogic.showChooseSexDailog();
                break;
            case R.id.tv_age_profile_edit:
                mLogic.showWheelView(age);
                break;
            case R.id.ll_profile_edit_phone:
                AccountSecurityActivity.start(this);
                break;

        }

    }

    @Override
    protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
        switch (requestCode) {
            case SYS_IMAGE_ACTIVITY_REQUEST_CODE:
                if (resultCode == RESULT_OK) {
                    if (data != null) {
                        Uri uri = data.getData();
                        String path = Dialoger.getPath(ProfileEditActivity.this, uri);
                        if (TextUtils.isEmpty(path)) {
                            ToastUtil.show(this, R.string.str_img_error);
                            return;
                        }
                        File file = ICUtils.getOutputMediaFile(ProfileEditActivity.this);
                        UCrop.Options options = new UCrop.Options();
                        options.setToolbarColor(Color.BLACK);
                        options.setActiveWidgetColor(Color.BLACK);
                        options.setStatusBarColor(Color.BLACK);
                        options.setHideBottomControls(true);
                        UCrop.of(Uri.fromFile(new File(path)), Uri.fromFile(file))
                                .withOptions(options)
                                .withAspectRatio(9, 9)
                                .withMaxResultSize(300, 300)
                                .start(ProfileEditActivity.this);
                    } else {
                        ToastUtil.show(mContext, R.string.str_img_error);
                    }
                }
                break;
            case CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE:
                if (RESULT_OK == resultCode) {
                    if (data != null) {
                        File file = ICUtils.getOutputMediaFile(ProfileEditActivity.this);
                        String path = data.getStringExtra("path");
                        if (TextUtils.isEmpty(path)) {
                            ToastUtil.show(this, R.string.str_img_error);
                            return;
                        }
                        UCrop.Options options = new UCrop.Options();
                        options.setToolbarColor(Color.BLACK);
                        options.setActiveWidgetColor(Color.BLACK);
                        options.setStatusBarColor(Color.BLACK);
                        options.setHideBottomControls(true);
                        UCrop.of(Uri.fromFile(new File(path)), Uri.fromFile(file))
                                .withOptions(options)
                                .withAspectRatio(9, 9)
                                .withMaxResultSize(300, 300)
                                .start(ProfileEditActivity.this);
                    } else {
                        ToastUtil.show(mContext, R.string.str_img_error);
                    }
                }
                break;
            case UCrop.REQUEST_CROP:
                if (RESULT_OK == resultCode) {
                    final Uri resultUri = UCrop.getOutput(data);
                    if (resultUri != null) {
                        imagePath = Dialoger.getPath(ProfileEditActivity.this, resultUri);
                        mLogic.upload();
                    }
                }
                break;
            default:
                super.onActivityResult(requestCode, resultCode, data);
                break;
        }
    }

    public String getImagePath() {
        return imagePath;
    }

    public void setResultUrl(String resultUrl) {
        this.resultUrl = resultUrl;
        GlideUtil.loadCircleImage(iv_head_img_profile_edit, resultUrl, R.mipmap.pnl_00_head108);
    }


    private void refreshView() {
        if (userModel != null) {
            GlideUtil.loadCircleImage(iv_head_img_profile_edit, userModel.getUser().getImgHead(),R.mipmap.pnl_00_head108);
            et_nickname_profile_edit.setText(userModel.getUser().getNick());
            et_website_profile_edit.setText(userModel.getWebsite());
            et_intro_profile_edit.setText(userModel.getIntro());
            tv_age_profile_edit.setText(userModel.getAge()==0?"":userModel.getAge()+ "");
            et_email_profile_edit.setText(userModel.getEmail());
            tv_sex_profile_edit.setText(mLogic.getSex(userModel.getUser().getSex()));
            CharSequence text = et_nickname_profile_edit.getText();
            if (text instanceof Spannable) {
                Spannable spanText = (Spannable) text;
                Selection.setSelection(spanText, text.length());
            }
            et_nickname_profile_edit.requestFocus();
            bindPhoneNumberView(userModel);

        }

    }

    private void bindPhoneNumberView(UserInfoModel model) {
        if (model.getPhone()==0){
            tv_phone_profile_edit.setTextColor(getResources().getColor(R.color.unread_point_bg));
            tv_phone_profile_edit.setText(R.string.setting_account_unbind);
        }else{
            tv_phone_profile_edit.setText(model.getPhone() + "");
            tv_phone_profile_edit.setTextColor(getResources().getColor(R.color.text_75));

        }
    }

    private void updateUserInfo() {
        if (TextUtils.isEmpty(et_nickname_profile_edit.getText())){
            ToastUtil.show(this,R.string.empty_nickname);
            return ;
        }
        if (SensitiveWordFilterManager.getInstance().hasSensitiveWord(et_nickname_profile_edit)){
            ToastUtil.show(this,R.string.sensitive_nickname);
            return ;
        }
        if (SensitiveWordFilterManager.getInstance().hasSensitiveWord(et_website_profile_edit)){
            ToastUtil.show(this,R.string.sensitive_website);
            return ;
        }
        if (SensitiveWordFilterManager.getInstance().hasSensitiveWord(et_email_profile_edit)){
            ToastUtil.show(this,R.string.sensitive_email);
            return ;
        }
        if (!TextUtils.isEmpty(et_email_profile_edit.getText())&&!AppUtil.isEmail(et_email_profile_edit.getText().toString())){
            ToastUtil.show(this,R.string.error_email);
            return ;
        }
        if (!StringUtil.isEmpty(resultUrl)) {
            userModel.getUser().setImgHead(resultUrl);
        }
        if (!TextUtils.isEmpty(et_nickname_profile_edit.getText())) {
            userModel.getUser().setNick(et_nickname_profile_edit.getText().toString());
        }
        if (age!=-1){
            userModel.setAge(age);
        }
        if (sex!=0){
            userModel.getUser().setSex(sex);
        }
        userModel.setWebsite(et_website_profile_edit.getText().toString());
        userModel.setIntro(et_intro_profile_edit.getText().toString());
        userModel.setEmail(et_email_profile_edit.getText().toString());

        DialogFragmentHelper.showLoadingDialog(getSupportFragmentManager(),"");
        ProtoRequestHelper.task(ProtoHttpFactory.updateUserInfo(userModel)).setTag(this.hashCode()).request(this);

}


    public void setSex(int sex) {
        this.sex = sex;
        tv_sex_profile_edit.setText(mLogic.getSex(sex));
    }


    public void setAge(int age) {
        this.age = age;
        tv_age_profile_edit.setText(age + "");
    }

    @Override
    public void onRequestSuccess(String command, String data) {
        DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());
        ResultNoData result = JSON.parseObject(data, ResultNoData.class);
        if (result.result==CodeSuccess){
            UserInfoCache.saveUserInfo(userModel);
            EventHelper.postUpdateUserInfo();
            finish();
            ToastUtil.show(this,R.string.save_success);
        }else{
            ErrorResult.toastError(this,result.result);
        }


    }

    @Override
    public void onRequestError(String command, int code, String message) {
        DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());
        if (code==110){
            try{
                Result<SensitiveWordResult> result = JSON.parseObject(message,new TypeReference<Result<SensitiveWordResult>>(){}.getType());
                ToastUtil.show(this,result.data.desc);
            }catch (Exception e){
                e.printStackTrace();
            }
        }else{
            ErrorResult.toastError(this,code);
        }
    }

    private void initUserInfoChangeListener(){
        userInfoChangeListener = new IMYTBASObject(false);
        userInfoChangeListener.stringCommand= EventHelper.EVENT_UPDATE_USER_INFO;
        userInfoChangeListener.setDataResultListener(new IMYTBASObject.OnDataResultListener() {
            @Override
            public void onCommandTaskSuccess(IMYTBASObject imytbasObject) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                           bindPhoneNumberView(UserInfoCache.getUserInfo());
                        }
                    });
                }
        });
        userInfoChangeListener.addEventListenWithTBASObject();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (userInfoChangeListener!=null){
            userInfoChangeListener.destroy();
        }
    }

    @Override
    protected boolean isTranslucentStatus() {
        return false;
    }

}
